package com.open.loan.controller;

import java.io.ByteArrayInputStream;	
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.open.loan.config.OSS.AliyunOSS;
import com.open.loan.domain.req.ReqDeleteFileModel;
import com.open.loan.domain.req.ReqUploadIdCardModel;
import com.open.loan.domain.req.ReqUploadInfoModel;
import com.open.loan.utils.BASE64DecodedMultipartFile;
import com.open.loan.utils.ResponseUtil;
import com.open.system.domain.LoanApplyDO;
import com.open.system.domain.LoanApplyLogDO;
import com.open.system.domain.LoanFaceDO;
import com.open.system.domain.LoanFileDO;
import com.open.system.domain.LoanProductDO;
import com.open.system.domain.LoanUserDO;
import com.open.system.service.LoanApplyLogService;
import com.open.system.service.LoanApplyService;
import com.open.system.service.LoanFaceService;
import com.open.system.service.LoanFileService;
import com.open.system.service.LoanProductService;
import com.open.system.service.LoanUserService;

import io.swagger.annotations.ApiOperation;
import sun.misc.BASE64Decoder;

@RestController
@RequestMapping("/moblie")
public class VueUploadImageController {
	
	@Autowired
	private LoanFileService loanFileService;
	
	@Autowired
	private LoanProductService loanProductService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanUserService loanUserService;
	
	@Autowired
	private LoanApplyLogService loanApplyLogService;
	
	@Autowired
	private LoanFaceService loanFaceService;
	
	
	@ApiOperation(value="上传借款合同", notes="")
	@RequestMapping(value ="/uploadImg",method = RequestMethod.POST)
	public ResponseEntity<String> uploadImgOrFile(@RequestBody ReqUploadInfoModel model,HttpServletRequest request,HttpServletResponse response){
				try{
					System.out.println(".....上传借口合同......");
					System.out.println(".....上传借口合同......");
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					if(model.getProductId()==null){
						ResponseUtil.toWrite("109","此产品已下架",null, response);
						return null;
					}
					
					LoanProductDO productDO=loanProductService.get(Long.parseLong(model.getProductId()));
					if(productDO==null){
						ResponseUtil.toWrite("109","此产品已下架",null, response);
						return null;
					}
					//对借贷开始申请
					LoanUserDO userDO=loanUserService.get(loanUserDo.getId());
					Map<String, Object> mapUserId=new HashMap<>();
					mapUserId.put("userId",loanUserDo.getId());
					List<LoanApplyDO>applyList=loanApplyService.list(mapUserId);
					if(applyList!=null && applyList.size()>0){
						LoanApplyDO applyDO=applyList.get(0);
						if(!"0".equals(applyDO.getStatus())&& !"5".equals(applyDO.getStatus()) && !"6".equals(applyDO.getStatus())){
							ResponseUtil.toWrite("1088","你还有一笔未结清，暂无法上传",null, response);
							return null;
						}
						
						applyDO.setStatus("0");
						userDO.setStatus("0");
						
						applyDO.setLoanProductId(productDO.getId());
						applyDO.setLoanProductName(productDO.getProductName());
						applyDO.setLoanRate(productDO.getLoanRate());
						applyDO.setLoanPeriod(productDO.getLoanDays());
						
						loanApplyService.update(applyDO);
						loanUserService.update(userDO);
					}else {
						LoanApplyDO applyDO=new LoanApplyDO();
						applyDO.setUserId(loanUserDo.getId());
						applyDO.setUserInfoAuth("0");//['0待完善', '1审核中', '2认证成功', '3认证失败']
						applyDO.setContactAuth("0");
						applyDO.setBankAuth("0");
						applyDO.setFaceAuth("0");
						applyDO.setCreditAuth("0");
						applyDO.setStatus("0");//借款状态 0 申请中, 1 待放款,2，放款中，3已放款  4，还款中，5已还清
						applyDO.setCreateTime(new Date());
						applyDO.setLoanProductId(productDO.getId());
						applyDO.setLoanProductName(productDO.getProductName());
						applyDO.setLoanRate(productDO.getLoanRate());
						applyDO.setLoanPeriod(productDO.getLoanDays());
						applyDO.setRemark6(loanUserDo.getMobile());
						applyDO.setRemark7(userDO.getRemark2());
						applyDO.setRemark8(userDO.getRemark3());
						loanApplyService.save(applyDO);
					}
					
					//applyLog表---------------------------------开始------------
					LoanApplyLogDO applyLogDO=loanApplyLogService.getLastNewData(mapUserId);
					LoanApplyLogDO applyDo=new LoanApplyLogDO();
					if((applyLogDO!=null && "5".equals(applyLogDO.getStatus()))||applyLogDO==null){
						applyDo.setUserId(loanUserDo.getId());
						applyDo.setStatus("0");
						applyDo.setCreateTime(new Date());
						if(StringUtils.isEmpty(userDO.getRealName())){
							applyDo.setRealName(userDO.getMobile());
						}else {
							applyDo.setRealName(userDO.getRealName());
						}
						applyDo.setProductId(productDO.getId());
						applyDo.setProductName(productDO.getProductName());
						applyDo.setLoanCycle(productDO.getLoanDays());
						loanApplyLogService.save(applyDo);
					}else {
						applyLogDO.setProductId(productDO.getId());
						applyLogDO.setProductName(productDO.getProductName());
						applyLogDO.setLoanCycle(productDO.getLoanDays());
						loanApplyLogService.update(applyLogDO);
					}
					//applyLog表---------------------------------结束------------
					
					String base64Images=model.getBase64Images();
					int num=1;
					
					List<LoanFileDO>fileList=loanFileService.list(mapUserId);
					if(fileList!=null && fileList.size()>0){
						num=fileList.size()+1;
					}
					String str=null;
					if(StringUtils.isEmpty(loanUserDo.getRealName())){
						str="-手机："+loanUserDo.getMobile();
					}else{
						str="-姓名："+loanUserDo.getRealName();
					}
					String fileName="ID："+loanUserDo.getId()+str+"-产品："+productDO.getProductName()+"-借款合同-"+num+".png";
					
					String endpoint=AliyunOSS.endpoint;
					String accessKeyId= AliyunOSS.accessKeyId;
					String accessKeySecret =AliyunOSS.accessKeySecret;
					String bucketName =AliyunOSS.bucketName;
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				    BASE64Decoder decoder = new BASE64Decoder(); 
				    String[] baseStrs = base64Images.split(",");
				    byte[] bytes = new byte[0];
				    bytes = decoder.decodeBuffer(baseStrs[1]);

			        for(int i = 0; i < bytes.length; ++i) {
			            if (bytes[i] < 0) {
			            	bytes[i] += 256;
			            }
			        }
				    
				    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);  
				    ossClient.putObject(bucketName,fileName,stream);
			        final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
			        long time = System.currentTimeMillis() + duration;
			        Date expiration = new Date(time);
			        URL  url=ossClient.generatePresignedUrl(bucketName,fileName, expiration);
					ossClient.shutdown();
					LoanFileDO loanFileDO=new LoanFileDO();
			        loanFileDO.setUserId(loanUserDo.getId());
			        loanFileDO.setRealName(loanUserDo.getRealName());
			        loanFileDO.setFileName(fileName);
			        loanFileDO.setFileUrl(url.toString());
			        loanFileDO.setCreateTime(new Date());
			        loanFileDO.setExpiredTime(expiration);
			        loanFileDO.setBucketName(bucketName);
			        loanFileDO.setEndpoint(endpoint);
			        loanFileDO.setRemark1("1");//合同
			        loanFileService.save(loanFileDO); 
			        Map<String,String>map=new HashMap<String,String>();
			        map.put("file_path",url.toString());
			        map.put("fileId",String.valueOf(loanFileDO.getId()));
			        ResponseUtil.toWrite("200","上传成功",map, response);
					return null;
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
	
	
		@ApiOperation(value="上传授权征信", notes="")
		@RequestMapping(value ="/uploadCreditImg",method = RequestMethod.POST)
		public ResponseEntity<String> uploadCreditImg(@RequestBody ReqUploadInfoModel model,HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					Map<String, Object> mapUserId=new HashMap<>();
					mapUserId.put("userId",loanUserDo.getId());
					String base64Images=model.getBase64Images();
					int num=1;
					
					List<LoanFileDO>fileList=loanFileService.list(mapUserId);
					if(fileList!=null && fileList.size()>0){
						num=fileList.size()+1;
					}
					String str=null;
					if(StringUtils.isEmpty(loanUserDo.getRealName())){
						str="-手机："+loanUserDo.getMobile();
					}else{
						str="-姓名："+loanUserDo.getRealName();
					}
					String fileName="ID："+loanUserDo.getId()+str+"-征信授权查询-"+num+".png";
					
					String endpoint=AliyunOSS.endpoint;
					String accessKeyId= AliyunOSS.accessKeyId;
					String accessKeySecret =AliyunOSS.accessKeySecret;
					String bucketName =AliyunOSS.bucketName;
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				    BASE64Decoder decoder = new BASE64Decoder(); 
				    
				    String[] baseStrs = base64Images.split(",");
				    byte[] bytes = new byte[0];
				    bytes = decoder.decodeBuffer(baseStrs[1]);

			        for(int i = 0; i < bytes.length; ++i) {
			            if (bytes[i] < 0) {
			            	bytes[i] += 256;
			            }
			        }
				    
				    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);  
				    ossClient.putObject(bucketName,fileName,stream);
			        final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
			        long time = System.currentTimeMillis() + duration;
			        Date expiration = new Date(time);
			        URL  url=ossClient.generatePresignedUrl(bucketName,fileName, expiration);
					ossClient.shutdown();
					LoanFileDO loanFileDO=new LoanFileDO();
			        loanFileDO.setUserId(loanUserDo.getId());
			        loanFileDO.setRealName(loanUserDo.getRealName());
			        loanFileDO.setFileName(fileName);
			        loanFileDO.setFileUrl(url.toString());
			        loanFileDO.setCreateTime(new Date());
			        loanFileDO.setExpiredTime(expiration);
			        loanFileDO.setBucketName(bucketName);
			        loanFileDO.setEndpoint(endpoint);
			        loanFileDO.setRemark1("2");//征信
			        loanFileService.save(loanFileDO); 
			        Map<String,String>map=new HashMap<String,String>();
			        map.put("file_path",url.toString());
			        map.put("fileId",String.valueOf(loanFileDO.getId()));
			        ResponseUtil.toWrite("200","上传成功",map, response);
					return null;
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
		
		//委托担保申请
		@ApiOperation(value="委托担保申请", notes="")
		@RequestMapping(value ="/uploadGuaranteeImg",method = RequestMethod.POST)
		public ResponseEntity<String> uploadGuaranteeImg(@RequestBody ReqUploadInfoModel model,HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					Map<String, Object> mapUserId=new HashMap<>();
					mapUserId.put("userId",loanUserDo.getId());
					String base64Images=model.getBase64Images();
					int num=1;
					
					List<LoanFileDO>fileList=loanFileService.list(mapUserId);
					if(fileList!=null && fileList.size()>0){
						num=fileList.size()+1;
					}
					String str=null;
					if(StringUtils.isEmpty(loanUserDo.getRealName())){
						str="-手机："+loanUserDo.getMobile();
					}else{
						str="-姓名："+loanUserDo.getRealName();
					}
					String fileName="ID："+loanUserDo.getId()+str+"-委托担保申请-"+num+".png";
					
					String endpoint=AliyunOSS.endpoint;
					String accessKeyId= AliyunOSS.accessKeyId;
					String accessKeySecret =AliyunOSS.accessKeySecret;
					String bucketName =AliyunOSS.bucketName;
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				    BASE64Decoder decoder = new BASE64Decoder(); 
				    
				    String[] baseStrs = base64Images.split(",");
				    byte[] bytes = new byte[0];
				    bytes = decoder.decodeBuffer(baseStrs[1]);

			        for(int i = 0; i < bytes.length; ++i) {
			            if (bytes[i] < 0) {
			            	bytes[i] += 256;
			            }
			        }
				    
				    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);  
				    ossClient.putObject(bucketName,fileName,stream);
			        final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
			        long time = System.currentTimeMillis() + duration;
			        Date expiration = new Date(time);
			        URL  url=ossClient.generatePresignedUrl(bucketName,fileName, expiration);
					ossClient.shutdown();
					LoanFileDO loanFileDO=new LoanFileDO();
			        loanFileDO.setUserId(loanUserDo.getId());
			        loanFileDO.setRealName(loanUserDo.getRealName());
			        loanFileDO.setFileName(fileName);
			        loanFileDO.setFileUrl(url.toString());
			        loanFileDO.setCreateTime(new Date());
			        loanFileDO.setExpiredTime(expiration);
			        loanFileDO.setBucketName(bucketName);
			        loanFileDO.setEndpoint(endpoint);
			        loanFileDO.setRemark1("3");//委托担保申请
			        loanFileService.save(loanFileDO); 
			        Map<String,String>map=new HashMap<String,String>();
			        map.put("file_path",url.toString());
			        map.put("fileId",String.valueOf(loanFileDO.getId()));
			        ResponseUtil.toWrite("200","上传成功",map, response);
					return null;
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
		
		@ApiOperation(value="上传身份证正反面", notes="")
		@RequestMapping(value ="/uploadIDCardImg",method = RequestMethod.POST)
		public ResponseEntity<String> uploadIDCardImg(@RequestBody ReqUploadIdCardModel model,HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					
					String base64Images=model.getBase64Images();
					
					String str="身份证照片";
					if("1".equals(model.getType())){
						str="身份证正面";
					}else if ("2".equals(model.getType())) {
						str="身份证反面";
					}else if ("3".equals(model.getType())) {
						str="手持身份证照片";
					}
					String fileName=loanUserDo.getId()+str+"-"+model.getType()+".png";
					
					String endpoint=AliyunOSS.endpoint;
					String accessKeyId= AliyunOSS.accessKeyId;
					String accessKeySecret =AliyunOSS.accessKeySecret;
					String bucketName =AliyunOSS.bucketName;
					// 创建OSSClient实例。
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				    BASE64Decoder decoder = new BASE64Decoder(); 
				    String[] baseStrs = base64Images.split(",");
				    byte[] bytes = new byte[0];
				    bytes = decoder.decodeBuffer(baseStrs[1]);

			        for(int i = 0; i < bytes.length; ++i) {
			            if (bytes[i] < 0) {
			            	bytes[i] += 256;
			            }
			        }
				    
				    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);  
				    ossClient.putObject(bucketName,fileName,stream);
			        final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
			        long time = System.currentTimeMillis() + duration;
			        Date expiration = new Date(time);
			        URL  url=ossClient.generatePresignedUrl(bucketName,fileName, expiration);
					ossClient.shutdown();
					//业务逻辑--开始
					loanUserDo=loanUserService.get(loanUserDo.getId());
					Map<String, Object> map=new HashMap<String, Object>();
					map.put("userId",loanUserDo.getId());
					List<LoanFaceDO>loanFaceList=loanFaceService.list(map);
					LoanFaceDO loanFaceDO=null;
					boolean hasFaceData=false;
					if(loanFaceList!=null && loanFaceList.size()>0){
						hasFaceData=true;
						loanFaceDO=loanFaceList.get(0);
					}else {
						hasFaceData=false;
						loanFaceDO=new LoanFaceDO();
						loanFaceDO.setUserId(loanUserDo.getId());
						loanFaceDO.setRealName(loanUserDo.getRealName());
						loanFaceDO.setCreateTime(new Date());
					}
						loanFaceDO.setScore("暂无、认证来源证件照片");
						loanFaceDO.setCreate("暂无、认证来源证件照片");
						loanFaceDO.setIdentify("暂无、认证来源证件照片");
						loanFaceDO.setFaceId1("1");
						loanFaceDO.setFaceId2("2");
						loanFaceDO.setFaceId3("3");
						if("1".equals(model.getType())){
							loanFaceDO.setPic1(url.toString());
						}else if ("2".equals(model.getType())) {
							loanFaceDO.setPic2(url.toString());
						}else if ("3".equals(model.getType())) {
							loanFaceDO.setPic3(url.toString());
						}
						loanFaceDO.setStatus("1");//1审核中
						
						//申请认证修改------开始
						List<LoanApplyDO>applyDOs=loanApplyService.list(map);
						if(applyDOs!=null && applyDOs.size()>0){
							LoanApplyDO applyDO=applyDOs.get(0);
							applyDO.setFaceAuth("1");//['0待完善', '1审核中', '2认证成功', '3认证失败']
							loanApplyService.update(applyDO);
							if(hasFaceData){
								loanFaceService.update(loanFaceDO);
							}else {
								loanFaceService.save(loanFaceDO);
							}
						}else {
							ResponseUtil.toWrite("209","请先认证银行卡信息",null, response);
							return null;
						}
					//业务逻辑--结束--
					
			        Map<String,String>JsonMap=new HashMap<String,String>();
			        JsonMap.put("file_path",url.toString());
			        ResponseUtil.toWrite("200","上传"+str+"成功",JsonMap, response);
					return null;
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
		
		@ApiOperation(value="显示授权征信", notes="")
		@RequestMapping(value ="/showCreditImg",method = RequestMethod.GET)
		public ResponseEntity<String> showCreditImg(HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					
					//对借贷开始申请
					Map<String, Object> mapUserId=new HashMap<>();
					mapUserId.put("userId",loanUserDo.getId());
					LoanFileDO fileDo=loanFileService.getLastNewInfo(mapUserId);
					Map<String, Object> jsonMap=new HashMap<>();
					if(fileDo==null){
						 ResponseUtil.toWrite("200","上传成功",null, response);
						 return null;
					}else {
						 jsonMap.put("url", fileDo.getFileUrl());
						 ResponseUtil.toWrite("200","上传成功",jsonMap, response);
						 return null;
					}
			       
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
		
		//委托担保申请
		@ApiOperation(value="委托担保申请", notes="")
		@RequestMapping(value ="/showGuaranteeImg",method = RequestMethod.GET)
		public ResponseEntity<String> showGuaranteeImg(HttpServletRequest request,HttpServletResponse response){
				try{
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					
					//对借贷开始申请
					Map<String, Object> mapUserId=new HashMap<>();
					mapUserId.put("userId",loanUserDo.getId());
					LoanFileDO fileDo=loanFileService.getLastNewGuaranteeInfo(mapUserId);
					Map<String, Object> jsonMap=new HashMap<>();
					if(fileDo==null){
						 ResponseUtil.toWrite("200","上传成功",null, response);
						 return null;
					}else {
						 jsonMap.put("url", fileDo.getFileUrl());
						 ResponseUtil.toWrite("200","上传成功",jsonMap, response);
						 return null;
					}
			       
					} catch (Exception e) {
						e.printStackTrace();
						ResponseUtil.toWrite("202","上传操作失败",null, response);
						return null;
					}
			}
	
	@ApiOperation(value="删除文件", notes="")
	@RequestMapping(value ="/deleteFile",method = RequestMethod.POST)
	public ResponseEntity<ReqDeleteFileModel>deleteFile(@RequestBody ReqDeleteFileModel  model,HttpServletRequest request,HttpServletResponse response){
				try {
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					if(StringUtils.isEmpty(model.getFileId())){
						ResponseUtil.toWrite("202","文件ID不存在",null, response);
						return null; 
					}
					if(loanFileService.remove(Long.parseLong(model.getFileId()))>0){
						ResponseUtil.toWrite("200","删除文件成功",null, response);
						return null; 
					}
					ResponseUtil.toWrite("209","删除文件失败",null, response);
					return null; 
				} catch (Exception e) {
					e.printStackTrace();
					ResponseUtil.toWrite("202","删除文件异常",null, response);
					return null;
				}
			}
	
	public static MultipartFile base64ToMultipart(String base64) {
	    try {
	        String[] baseStrs = base64.split(",");

	        BASE64Decoder decoder = new BASE64Decoder();
	        byte[] b = new byte[0];
	        b = decoder.decodeBuffer(baseStrs[1]);

	        for(int i = 0; i < b.length; ++i) {
	            if (b[i] < 0) {
	                b[i] += 256;
	            }
	        }

	        return new BASE64DecodedMultipartFile(b, baseStrs[0]);
	    } catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
	}
	
}
